package cn.bone.zk.zk02;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;

public class ZkServer {

    private String name;
    private ZooKeeper zkClient;

    public ZkServer(String name){
        this.name = name;
    }

    public void start(){
        init();
        existParent();
        creatChildren();
    }

    // 1.创建连接
    public void init(){

        String connectString = "192.168.1.5:2001,192.168.1.5:2002,192.168.1.5:2003";
        int sessionTimeout = 2000;
        try {
            zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
                @Override
                public void process(WatchedEvent event) {

                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // 2.判断父节点在不在，如果不在创建父节点 /servers
    public void existParent(){
        Stat stat = null;
        try {
            stat = zkClient.exists("/servers", false);
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(stat==null){
            try {
                zkClient.create("/servers",
                        "servers".getBytes(),
                        ZooDefs.Ids.OPEN_ACL_UNSAFE,
                        CreateMode.PERSISTENT);
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    // 3.创建临时子节点 /server/{name}
    // 这里也可以考虑使用相同的子节点名字，创建临时带序号的子节点
    public void creatChildren(){
        try {
            zkClient.create("/servers/" + name,
                    name.getBytes(),
                    ZooDefs.Ids.OPEN_ACL_UNSAFE,
                    CreateMode.EPHEMERAL);
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
